package com.zhu.storesmanager.views;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.zhu.storesmanager.R;
import com.zhu.storesmanager.SvStoreCompeteActivity;
import com.zhu.storesmanager.models.CompeteProductItem;
import com.zhu.storesmanager.models.DataItem;
import com.zhu.storesmanager.utils.Actions;
import com.zhu.storesmanager.utils.DataUtils;
import com.zhu.storesmanager.utils.DatabaseUtil;
import com.zhu.storesmanager.utils.ViewsUtil;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * 新产品上市信息 或者 活动信息
 */
public class NewProductsView extends LinearLayout implements OnClickListener{

    private static final int PICK_FROM_CAMERA = 0;
    private static final int CROP_FROM_CAMERA = 1;

    private ChoiceView mBrandChoiceview = null; //品牌
    private EditText mModelEditText = null; //型号
    private ChoiceView mFunctionsChoiceview = null; //功能或者活动
    private EditText mPriceEditText = null; //价格
    private EditText mOtherEditText = null; //其他功能或者其他活动
    private EditText mSellcountEditText = null; //销量
    private CheckBox mCheckBox = null; //选中框
    private Activity mActivity = null;
    private boolean isImageChange = false;
    private boolean isTakingPhoto = false; //正在拍照
    private Uri mImageCaptureUri = null;
    private CompeteProductItem mTakeCompeteProductItem = null; //正在拍照项
    private PopCompeteInfoView mPopCompeteInfoView = null; //详情界面

    private List<CompeteProductItem> mDataList = new ArrayList<CompeteProductItem>();
    private int mType = SvStoreCompeteActivity.TYPE_COMPETE_CONTENT_FUCTION;
    
    private LinearLayout mBodyLinearLayout = null; //新增项

    public NewProductsView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }

    public NewProductsView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    public NewProductsView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
    }

    /**
     * 界面加载
     */
    public void setupView(){
        if(mType == SvStoreCompeteActivity.TYPE_COMPETE_CONTENT_ACTIVITY){
            mBrandChoiceview = ViewsUtil.setChoiceView(findViewById(R.id.compete_brands), R.string.sales_brands);
            mModelEditText = ViewsUtil.setEditTextView(findViewById(R.id.compete_model), R.string.model);
            mPriceEditText = ViewsUtil.setEditTextView(findViewById(R.id.compete_price), R.string.price);
            mSellcountEditText = ViewsUtil.setEditTextView(findViewById(R.id.compete_sellcount), R.string.salescount);
            mFunctionsChoiceview = ViewsUtil.setChoiceView(findViewById(R.id.compete_apromotions), R.string.compete_activity);
            mFunctionsChoiceview.setMultiChoice();
            mOtherEditText = ViewsUtil.setEditTextView(findViewById(R.id.compete_otherpromotions), R.string.compete_otheractivity);
        }else{
            mBrandChoiceview = ViewsUtil.setChoiceView(findViewById(R.id.compete_brands), R.string.sales_brands);
            mModelEditText = ViewsUtil.setEditTextView(findViewById(R.id.compete_model), R.string.model);
            mPriceEditText = ViewsUtil.setEditTextView(findViewById(R.id.compete_price), R.string.price);
            mFunctionsChoiceview = ViewsUtil.setChoiceView(findViewById(R.id.compete_functions), R.string.function);
            mFunctionsChoiceview.setMultiChoice();
            mOtherEditText = ViewsUtil.setEditTextView(findViewById(R.id.compete_otherfunctions), R.string.otherfunction);
        }
        mCheckBox = (CheckBox)findViewById(R.id.compete_check); 
        findViewById(R.id.compete_newadd).setOnClickListener(this);
        mBodyLinearLayout = (LinearLayout)findViewById(R.id.compete_body);
        if(DataUtils.mUserData.isAdmin()){ //管理员隐藏输入框
        	findViewById(R.id.operate).setVisibility(View.GONE);
        	findViewById(R.id.compete_brands).setVisibility(View.GONE);
        	if(findViewById(R.id.compete_apromotions) != null){
        		findViewById(R.id.compete_apromotions).setVisibility(View.GONE);
        	}
        	if(findViewById(R.id.compete_functions) != null){
        		findViewById(R.id.compete_functions).setVisibility(View.GONE);
        	}
        	findViewById(R.id.compete_model).setVisibility(View.GONE);
        	findViewById(R.id.compete_price).setVisibility(View.GONE);
        	if(findViewById(R.id.compete_sellcount) != null){
        		findViewById(R.id.compete_sellcount).setVisibility(View.GONE);
        	}
        	if(findViewById(R.id.compete_otherpromotions) != null){
        		findViewById(R.id.compete_otherpromotions).setVisibility(View.GONE);
        	}
        	if(findViewById(R.id.compete_otherfunctions) != null){
        		findViewById(R.id.compete_otherfunctions).setVisibility(View.GONE);
        	}
        	mCheckBox.setEnabled(false);
        	findViewById(R.id.compete_newadd).setVisibility(View.GONE);
        }
    }

    /**
     * 初始化界面类型
     * @param activity
     * @param type 类型  2==新品功能  3==竞品活动
     */
    public void init(Activity activity, PopCompeteInfoView popCompeteInfoView, int type){
        mPopCompeteInfoView = popCompeteInfoView;
        mActivity = activity;
        mType = type;
        setupView();
    }

    /**
     * (non-Javadoc)
     * @see android.view.View.OnClickListener#onClick(android.view.View)
     */
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if(v != null){
            switch(v.getId()){
                case R.id.compete_newadd: //新增
                    addNewProductData();
                    break;
                case R.id.compete_delete:
                    deleteData((CompeteProductItem)v.getTag()); //删除
                    break;
                case R.id.compete_takephoto: //拍照
                    doTakePhotoAction((CompeteProductItem)v.getTag());
                    break;
                case R.id.compete_item: //详情
                    if(mType == SvStoreCompeteActivity.TYPE_COMPETE_CONTENT_ACTIVITY){
                        mPopCompeteInfoView.showPopView((CompeteProductItem)v.getTag(), mType, R.string.compete_promotions);   
                    }else{
                        mPopCompeteInfoView.showPopView((CompeteProductItem)v.getTag(), mType, R.string.compete_newproduct);
                    }
                    break;
            }
        }
    }

    /**
     * 设置选项数据
     * @param brandsList 品牌选项
     * @param fuctionsList 功能
     */
    public void setChoiceviewList(List<DataItem> brandsList, List<DataItem> fuctionsList){
        mBrandChoiceview.setChoiceDataList(brandsList);
        mFunctionsChoiceview.setChoiceDataList(fuctionsList);
    }

    /**
     * 添加竞品型号加个数据界面
     * @param dataItem 品牌数据
     */
    private void addDataView(CompeteProductItem dataItem){
        View view = LayoutInflater.from(getContext()).inflate(R.layout.view_competeinfo_item, null);
        view.setOnClickListener(this);
        view.setTag(dataItem);
        ViewsUtil.setTextViewData(view, R.id.compete_name, dataItem.mBrandName);
        ViewsUtil.setTextViewData(view, R.id.compete_model, dataItem.mModelName);
        ViewsUtil.setTextViewData(view, R.id.compete_price, dataItem.mPrice);
        View delete = view.findViewById(R.id.compete_delete);
        View takephoto = view.findViewById(R.id.compete_takephoto);
        if(DataUtils.mUserData.isAdmin()){ //管理员隐藏操作
        	delete.setVisibility(View.GONE);
        	takephoto.setVisibility(View.GONE);
        }else{
        	takephoto.setOnClickListener(this);
            takephoto.setTag(dataItem);
            delete.setOnClickListener(this);
            delete.setTag(dataItem);
        }
        mBodyLinearLayout.addView(view);
    }

    /**
     * 添加新产品
     */
    private void addNewProductData(){
        String brandID = mBrandChoiceview.getSaveData();
        String model = mModelEditText.getText().toString();
        String price = mPriceEditText.getText().toString().trim();
        String dataIDs = mFunctionsChoiceview.getSaveData();
        if(brandID != null && brandID.length() > 0 && model != null && model.length() > 0 && price != null && price.length() > 0
                && dataIDs != null && dataIDs.length() > 0){
            CompeteProductItem item = new CompeteProductItem();
            item.mBrandId = brandID;
            item.mBrandName = mBrandChoiceview.getSelectedText();
            item.mModelName = model;
            item.mPrice = price;
            item.mDataIDs = dataIDs;
            item.mDataNames = mFunctionsChoiceview.getSelectedText();
            item.mOther = mOtherEditText.getText().toString();
            if(mType == SvStoreCompeteActivity.TYPE_COMPETE_CONTENT_ACTIVITY){
                item.mSellcount = mSellcountEditText.getText().toString().trim();
            }
            addNewProductData(item);
        }else{
            Actions.toastShort(getContext(), R.string.compete_price_notnull);
        }
    }

    /**
     * 添加新产品
     * @param dataItem 新产品数据
     */
    public void addNewProductData(CompeteProductItem dataItem){
        if(checkDatadDuplication(dataItem)){
            Actions.toastShort(getContext(), R.string.compete_data_duplication);
            return;
        }
        mDataList.add(dataItem);
        addDataView(dataItem);
    }


    /**
     * 删除数据项
     * @param dataItem 产品数据
     */
    private void deleteData(CompeteProductItem dataItem){
        int index = mDataList.indexOf(dataItem);
        mDataList.remove(index);
        mBodyLinearLayout.removeViewAt(index);
        if (dataItem.mPhoto != null && !dataItem.mPhoto.isRecycled()) { //如果存在照片则清空照片数据
            dataItem.mPhoto.recycle();
            dataItem.mPhoto = null;
        }
        dataItem = null;
    }

    /**
     * 检查数据是否重复
     * @param dataItem 产品数据
     * @param true 数据重复 否则反之
     */
    private boolean checkDatadDuplication(CompeteProductItem dataItem){
        for(CompeteProductItem item : mDataList){
            if(item.mBrandId.equals(dataItem.mBrandId) && item.mModelName.equals(dataItem.mModelName)){
                return true;
            }
        }
        return false;
    }

    /**
     * 处理照相
     * @param competeProductItem 竞品项
     */
    private void doTakePhotoAction(CompeteProductItem competeProductItem) {
        mTakeCompeteProductItem = competeProductItem;
        isTakingPhoto = true;
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                            "tmp_contact_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
        intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
        try {
            intent.putExtra("return-data", true);
            mActivity.startActivityForResult(intent, PICK_FROM_CAMERA);
        } catch (ActivityNotFoundException e) {
            // Do nothing for now
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            isTakingPhoto = false;
            return;
        }
        switch (requestCode) {
            case CROP_FROM_CAMERA:
                final Bundle extras = data.getExtras();
                if (extras != null) {
                    if(mTakeCompeteProductItem.mPhoto != null && !mTakeCompeteProductItem.mPhoto.isRecycled()){
                        mTakeCompeteProductItem.mPhoto.recycle();
                    }
                    Bitmap tem = extras.getParcelable("data");
                    mTakeCompeteProductItem.mPhoto = makeTextBitMap(tem);
                }
                File f = new File(mImageCaptureUri.getPath());
                if (f.exists()) {
                    f.delete();
                }
                isTakingPhoto = false;
                break;
            case PICK_FROM_CAMERA: //切图
                Intent intent = new Intent("com.android.camera.action.CROP");
                intent.setDataAndType(mImageCaptureUri, "image/*");
                intent.putExtra("outputX", 320);
                intent.putExtra("outputY", 240);
                intent.putExtra("return-data", true);
                mActivity.startActivityForResult(intent, CROP_FROM_CAMERA);
                break;
        }
    }

    /**
     * 图片加水印
     * @param bitmap 原图
     */
    private Bitmap makeTextBitMap(Bitmap bitmap) {
//        Canvas canvasTemp = new Canvas(bitmap);
//        canvasTemp.drawColor(Color.TRANSPARENT);
//        Paint p = new Paint();
//        p.setColor(Color.RED);
//        p.setAntiAlias(true);
//        p.setTextSize(22);
//        canvasTemp.drawText(Util.mVerifyUserResult.name, 0, 170, p);
//        canvasTemp.drawText(Util.getFormatTime(), 0, 200, p);
        return bitmap;
    }

    /**
     * 是否正在拍照
     */
    public boolean isTakePhoto(){
        return isTakingPhoto;
    }

    /**
     * 保存数据
     * @param storeId 门店ID
     */
    public void saveData(String storeId){
        if(mDataList.size() > 0 && mCheckBox.isChecked()){
            DatabaseUtil.saveCompeteData(getContext(), mDataList, storeId, mType);
        }
    }

    /**
     * 是否能保存数据
     * @param true 可以
     */
    public boolean canSaveData(){
    	for(CompeteProductItem item : mDataList){
    		if(item.mPhoto == null){ //检测是否拍照否则不让起保存
    			return false;
    		}
    	}
    	return true;
    }
    /**
     * 设置标签文本
     * @param text
     */
    public void setLableText(String text){
    	mCheckBox.setText(text);
    }

    /**
     * 是不是空数据
     * @param isShow 是否显示
     */
    public boolean checkData(boolean isShow){
    	if(isShow && mCheckBox.isChecked()){
    		if(mDataList != null && mDataList.size() > 0){
    			return true;
    		}else{
    			return false;
    		}
    	}
    	return true;
    }

    /**
     * 是否选中
     */
    public boolean isSelect(){
    	return mCheckBox.isChecked();
    }

    /**
     * 设置选中状态
     */
    public void setSelectStatus(boolean select){
    	mCheckBox.setChecked(select);
    }
}
